<?php

namespace app\system\controller\customer;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use hehe\Numeral;
use hehe\Str;
use hehe\Trade;
use think\facade\Db;


class OrderBill extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['notes'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\customer\OrderBill;
    }




    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $this->withJoinTable = ['product' => function($query){
            $query->leftJoin(['category']);
        }];
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->alias($alias)
            ->where($where);
        $param = $this->request->param();
//        echo 1 ;die;

        if(!empty($param['order_id'])){
            $res = $res->where(['order_id' => $param['order_id']]);
        }

        $res = $res->where(['type' => $param['type']]);


        $res = $res->order('id asc')->paginate($limit);
//        echo 1;die;

        $list = $res->items();

//        print_r($list);die;

        foreach($list as $key => $val){
            $list[$key]['amount'] = $val['currency'] . ' ' . ($val['amount'] / $this->multiply);
            $list[$key]['create_time'] = date('Y-m-d', $val['create_time']);
        }


        $this->success('', [
            'list' => $list,
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }



            $data['create_time'] = strtotime($data['create_time']);
            $data['amount'] = $data['amount'] * $this->multiply;



//            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }



//

            if($data['type'] == 'collection'){
                $order = db::name('customer_order')->where(['id' => $data['order_id']])->find();
                if($order['amount'] <= 0) $this->error(__('未设置订单总价，无法添加收款记录'));
            }
//            print_r($data);die;

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                if($data['type'] == 'collection'){
                    $pay_amount = db::name('order_bill')->where(['order_id' => $data['order_id'], 'type' => $data['type']])->sum('amount');
                    $result = db::name('customer_order')->where(['id' => $data['order_id']])->update([
                        'pay_amount' => $pay_amount / $this->multiply * 100,
                        'update_time' => $this->timestamp
                    ]);
                }


                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data['create_time'] = strtotime($data['create_time']);
            $data['amount'] = $data['amount'] * $this->multiply;

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                if($data['type'] == 'collection'){
                    $pay_amount = db::name('order_bill')->where(['order_id' => $data['order_id'], 'type' => $data['type']])->sum('amount');
                    $result = db::name('customer_order')->where(['id' => $data['order_id']])->update([
                        'pay_amount' => $pay_amount / $this->multiply * 100,
                        'update_time' => $this->timestamp
                    ]);
                }


                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $row['amount'] /= $this->multiply;
        $row['create_time'] = date('Y-m-d', $row['create_time']);

        $this->success('', [
            'row' => $row
        ]);
    }











    public function del(array $ids = []): void
    {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }

        $where             = [];
        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $where[] = [$this->dataLimitField, 'in', $dataLimitAdminIds];
        }

        $pk      = $this->model->getPk();
        $where[] = [$pk, 'in', $ids];

        $count = 0;
        $data  = $this->model->where($where)->select();
        $this->model->startTrans();
        try {
            foreach ($data as $v) {

                $order_id = $v->order_id;
                $type = $v->type;
                $count += $v->delete();

            }
            if($type == 'collection'){
                $amount = db::name('order_bill')->where(['order_id' => $order_id, 'type' => $type])->sum('amount');
                db::name('customer_order')->where(['id' => $order_id])->update([
                    'pay_amount' => $amount / $this->multiply * 100,
                    'update_time' => $this->timestamp
                ]);
            }


            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }















}